import React from "react";
import styles from "./index.module.css";
import { AppState, AppThunkDispatch } from "@src/index";
import { UserCreators } from "@src/store/creators/UserCreators";
import { UserActions } from "@src/store/actions/userActions";
import { UserState } from "@src/store/reducers/userReducer";
import {
  connect,
  MapDispatchToPropsParam,
  MapStateToPropsParam,
} from "react-redux";
import Confirm from "../confirm";
import { history } from "@src/App";

// 组件状态类型
interface States {
  // 控制退出登录弹窗是否渲染
  isOpen: boolean;
}

class Header extends React.Component<Props, States> {
  constructor(props: Props) {
    super(props);
    this.state = {
      isOpen: false,
    };
  }
  async componentDidMount() {
    await this.props.requestUserInfo().then((response) => {});
  }
  render() {
    // 检测用户信息是否获取成功
    if (this.props.user.user.status !== "success") return;
    return (
      <div className={styles.header}>
        <div className={styles.logo}>
          <img src={require("../../assetc/image/logo.png")} alt="极客园" />
        </div>
        <div className={styles.user}>
          <span>{this.props.user.user.result.name}</span>
          <button
            className="button is-ghost has-text-white"
            onClick={() => this.setState({ isOpen: true })}
          >
            退出
          </button>
          <Confirm
            isOpen={this.state.isOpen}
            close={() => this.setState({ isOpen: false })}
            onSureButtonClicked={() => {
              // 清空用户信息
              this.props.clearUser();
              // 跳转登录页
              history.replace("/login");
            }}
            onCancelButtonClicked={() => {
              this.setState({ isOpen: false });
            }}
          >
            您确定要退出登录吗?
          </Confirm>
        </div>
      </div>
    );
  }
}

interface StateProps {
  user: UserState;
}

interface OwnProps {}

interface DispatchProps {
  requestUserInfo: () => Promise<UserActions.Actions>;
  // 清空用户信息
  clearUser: () => UserActions.Actions;
}

type Props = StateProps & DispatchProps & OwnProps;

const mapStateToProps: MapStateToPropsParam<StateProps, OwnProps, AppState> = (
  state
) => ({
  // 获取用户状态对象
  user: state.userReducer,
});

const mapDispatchToProps: MapDispatchToPropsParam<DispatchProps, OwnProps> = (
  dispatch: AppThunkDispatch
) => ({
  // 获取用户信息
  requestUserInfo: () => dispatch(UserCreators.requestUserInfo()),
  // 清空用户信息
  clearUser: () => dispatch(UserCreators.claerUser()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Header);
